package com.five.admin.rabbit;

import com.five.admin.cache.OrderCaffeineCache;
import com.five.admin.config.RabbitConfig;
import com.five.admin.redis.OrderRedisCache;
import com.five.event.OrderChangeEvent;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class OrderCacheClearConsumer {

    @Resource
    private OrderRedisCache redisCache;
    @Resource
    private OrderCaffeineCache caffeineCache;

    // 监听订单缓存更新队列
    @RabbitListener(queues = RabbitConfig.ORDER_CACHE_UPDATE_QUEUE)
    public void clearCache(OrderChangeEvent event,
                           Channel channel,
                           @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        try {
            log.info("开始处理缓存清除消息：userId={}, orderNo={}", event.getUserId(), event.getOrderNo());
            Long userId = event.getUserId();
            String orderNo = event.getOrderNo();
            String cacheKey = userId + ":" + orderNo;

            // 清除本地Caffeine缓存
            caffeineCache.getOrderDetailCache().invalidate(cacheKey);
            caffeineCache.getOrderStatusCache().invalidate(cacheKey);
            caffeineCache.getOrderListCache().asMap().keySet().removeIf(key -> key.startsWith(userId + ":"));

            // 清除Redis缓存
            redisCache.clearOrderCache(userId, orderNo);

            log.info("缓存清除完成：userId={}, orderNo={}", userId, orderNo);
            // 手动确认消息（成功处理）
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("缓存清除失败", e);
            // 拒绝消息并转发到死信队列（不重回队列）
            channel.basicNack(deliveryTag, false, false);
        }
    }
}